package com.pzl.projection.push;

import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.pzl.projection.push.other.DebugUtil;

//网上免费的websoket测试  http://www.websocket-test.com/

//截屏数据推流端
public class MainActivity extends AppCompatActivity {
    final String TAG = "jinx_projection";

    //设备屏幕录屏、截屏系统服务
    MediaProjectionManager mediaProjectionManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((TextView) findViewById(R.id.tvProjectionPushIP)).setText(DebugUtil.getLocalIpAddress(this));

        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    }

    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_projection_reqPermi:
                DebugUtil.port = Integer.parseInt(((EditText) findViewById(R.id.etProjectionPushPort)).getText().toString().trim());
                //请求获取用户截取屏幕的授权
                Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
                startActivityForResult(captureIntent, 2);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ////获取到了截屏用户屏幕的许可
        if (requestCode == 2 && resultCode == RESULT_OK) {
            Log.i(TAG, "已允许截取用户的手机屏幕");
            Toast.makeText(this, "已允许截取用户的手机屏幕", Toast.LENGTH_LONG).show();

            Intent foregroundService = new Intent(this, ScreenDisplayService.class);
            foregroundService.putExtra("resultCode", resultCode);
            foregroundService.putExtra("data", data);
            startMyService(foregroundService);
        }

    }


    private void startMyService(Intent foregroundService) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(foregroundService);
        } else {
            startService(foregroundService);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent foregroundService = new Intent(this, ScreenDisplayService.class);
        stopService(foregroundService);
    }

}